package com.yyk.yiliao.ui.activity.dingdan.fragment;


import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseFragment;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.ui.activity.dingdan.activity.DingdanXiangqing4_Activity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.DialogUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.bean.CartOrderlist;
import com.yyk.yiliao.bean.CartStatuskey_Info;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.OrderOrderRestart_Info;
import com.yyk.yiliao.widget.diver.CustomDecoration;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.Unbinder;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class Tab_Three_Fragment extends BaseFragment {
    public static final String ARGS_PAGE = "Tab_Three_Fragment";
    @BindView(R.id.nTab_rv)
    RecyclerView nTab_rv;
    private Unbinder unbinder;


    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private BaseRecyclerAdapter<CartOrderlist.DataBean> adapter;
    private List<CartOrderlist.DataBean> data = new ArrayList<>();

    private int currentPage = 1;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_tab1;
    }

    @Override
    public void initView() {

        initRefreshLoadMore();
    }

    @Override
    public void initData() {
        initAdapter();
    }

    private void initAdapter() {
        adapter = new BaseRecyclerAdapter<CartOrderlist.DataBean>(getActivity(), data, R.layout.adapter_item_c_tab_three) {
            @Override
            public void convert(BaseRecyclerHolder holder, CartOrderlist.DataBean info, final int position, boolean isScrolling) {
                TextView tv_confirm = holder.getView(R.id.tv_confirm);
                int status = info.getStatus();
                if (status == 3) {
                    holder.setText(R.id.tv_status, "等待商家发货");
                    tv_confirm.setVisibility(View.GONE);
                } else if (status == 4) {
                    holder.setText(R.id.tv_status, "待收货");
                    tv_confirm.setVisibility(View.VISIBLE);
                }
                holder.setText(R.id.tv_stname, info.getStname());
                holder.setText(R.id.tv_total_num, "共" + info.getAllnum() + "件商品 已付款：");
                holder.setText(R.id.tv_total_money, "¥" + info.getAllmoney());
                final String number = String.valueOf(info.getNumber());
                RecyclerView rv = holder.getView(R.id.rv);
                tv_confirm.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        AlertDialog builder = DialogUtil.getIntanse().simpleDialog(getContext(), null, "确定已收到货品？", "确定收货", "取消", new DialogUtil.AlertDialogListenter() {
                            @Override
                            public void queding() {
                                initQuerenDingdan(number, 5, position);
                            }

                            @Override
                            public void quxiao() {

                            }
                        });

                        builder.show();
                    }
                });
                rv.setLayoutManager(new LinearLayoutManager(getContext()));
                rv.addItemDecoration(new CustomDecoration(getActivity(), CustomDecoration.VERTICAL_LIST, R.drawable.divider_f8_shopdingdan, 0));
                BaseRecyclerAdapter<CartOrderlist.DataBean.ListBean> baseRecyclerAdapter = new BaseRecyclerAdapter<CartOrderlist.DataBean.ListBean>(getContext(), info.getList(), R.layout.adapter_item_c_tab_three_three) {

                    @Override
                    public void convert(BaseRecyclerHolder holder, CartOrderlist.DataBean.ListBean item, int position, boolean isScrolling) {
                        holder.setText(R.id.tv_sname, item.getSname());
                        holder.setText(R.id.tv_money, "¥" + item.getMoney());
                        holder.setText(R.id.tv_num, "X" + item.getNum());
                        holder.setImageByUrl(R.id.iv_img, ApiService.BASE_URL + item.getImg());

                    }
                };
                rv.setAdapter(baseRecyclerAdapter);
                baseRecyclerAdapter.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(RecyclerView parent, View view, int pp) {
                        initDingDanXiangqing(data.get(position).getNumber(), position, data.get(position).getStatus());
                    }
                });
            }
        };
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        nTab_rv.setLayoutManager(linearLayoutManager);
        nTab_rv.addItemDecoration(new CustomDecoration(getActivity(), CustomDecoration.VERTICAL_LIST, R.drawable.divider_f8_10, 0));
        nTab_rv.setAdapter(adapter);


    }

    private void initRefreshLoadMore() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                currentPage++;
                setThree(currentPage, false);
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                setThree(currentPage, true);
                refreshLayout.finishRefresh();
            }
        });
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        super.onFragmentVisibleChange(isVisible);
        if (isVisible) {
            currentPage = 1;
            setThree(currentPage, true);
        }
    }

    public static Tab_Three_Fragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARGS_PAGE, page);
        Tab_Three_Fragment fragment = new Tab_Three_Fragment();
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 待收货
     *
     * @param currentPage
     * @param flag
     */
    private void setThree(int currentPage, final boolean flag) {
        Map<String, String> map = new TreeMap<>();

        map.put("uid", String.valueOf(Hawk.get("uid", 0)));
        map.put("status", "34");
        map.put("page", String.valueOf(currentPage));
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartOrderlist(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartOrderlist>() {


                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();


                    }

                    @Override
                    public void onNext(CartOrderlist info) {
                        Logger.e("待收货" + info.toString());
                        if (info.getCode() == 1) {
                            if (flag) {
                                data.clear();
                            }
                            if (null != info.getData() && info.getData().size() > 0) {
                                data.addAll(info.getData());
                            } else {
                                ToastUtil.showShort(getActivity(), "已经没有数据了");
                            }
                            adapter.notifyDataSetChanged();
                            adapter.onAttachedToRecyclerView(nTab_rv);
                        } else {
//                            ToastUtil.showShort(getActivity(), "全部没有数据");
                        }

                    }


                });
        try {
            //因为网络请求在子线程，所以不能让宿主线程过早的结束。
            Thread.sleep(100);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }


    }

    /**
     * 确认收货
     *
     * @param id
     * @param status
     * @param postion
     */
    public void initQuerenDingdan(String id, int status, final int postion) {
        Map<String, String> map = new TreeMap<>();

        map.put("number", id + "");
        map.put("status", status + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartStatuskey(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartStatuskey_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(CartStatuskey_Info info) {
                        if (info.getCode() == 1) {
//                            ToastUtil.showShort(getActivity(), info.getMsg());
                            adapter.delete(postion);
//                            setThree();
                        }
                    }
                });
    }

    /**
     * 订单详情  待收货
     *
     * @param id
     * @param postion
     */
    private void initDingDanXiangqing(String id, final int postion, final int status) {
        Map<String, String> map = new TreeMap<>();

        map.put("type", "2");
        map.put("order_code", id + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postOrderOrderRestart(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<OrderOrderRestart_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(OrderOrderRestart_Info info) {
                        if (info.getCode() == 1) {
                            info.setPostion(postion);
                            info.setZkstatus(status);
                            Intent intent = new Intent(getActivity(), DingdanXiangqing4_Activity.class);
                            EventBus.getDefault().postSticky(info);
                            startActivity(intent);

                        } else {
                        }
                    }
                });
    }


}
